from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views import View


class SmsCodeView(View):
    def get(self, request, mobile):
        # 1 获取参数
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        # 2 验证参数
        if not all([image_code, uuid]):
            return JsonResponse({'code': '400', 'errmsg': '参数不全'})
        # 3 验证图片验证码
        # 3.1 连接redis
        from django_redis import get_redis_connection
        redis_cli = get_redis_connection('code')
        # 3.2 获取redis数据
        redis_image_code = redis_cli.get(uuid)
        redis_send_flag = redis_cli.get('send_flag_%s'%mobile)
        if redis_send_flag is not None:
            return JsonResponse({'code': '400', 'errmsg': 'not again send message'})
        if redis_image_code is None:
            return JsonResponse({'code': '400', 'errmsg': '验证码过期'})
        # 3.3 对比
        if redis_image_code.decode().lower() != image_code.lower():
        #if redis_image_code != image_code:
            return JsonResponse({'code': '400', 'errmsg': '图片验证码错误'})
        # 4 生成短信验证码（测试的时候，验证码是1-4位的数字，这里都设置为4位）
        from random import randint
        sms_code = '%04d' % randint(0, 9999)
        # 5 保存短信验证码到redis的code库
        pl = redis_cli.pipeline()
        pl.setex(mobile, 300, sms_code)
        pl.setex('send_flag_%s'%mobile, 300, 1)
        pl.execute()
        #redis_cli.setex(mobile, 300, sms_code)
        #redis_cli.setex('send_flag_%s'%mobile, 300, 1)
        # 6 发送短信验证码给手机。可以将测试发送短息的功能，封装成一个类
        # tid = '1' , mobile = '13080797453', datas = ('6666', '120秒')
        # from libs.phone_mssg.send_mssg import send_message
        # send_message(1, mobile, (sms_code, '5min'))
        from celery_tasks.sms.tasks import celery_send_msg_code
        celery_send_msg_code.delay(mobile, sms_code)

        # 7 返回响应
        return JsonResponse({'code': '0', 'errmsg': 'ok'})


# Create your views here.
class ImageCodeView(View):
    def get(self, request, uuid):
        # 2 生成图片验证码和图片二进制
        from libs.captcha.captcha import captcha
        # text 是图片验证码的内容 例如 xyzz
        # image 是 图片二进制
        text, image = captcha.generate_captcha()

        # 3 通过redis 把图片验证码和 uuid关联保存起来
        from django_redis import get_redis_connection
        # 3.1 进行reids连接
        redis_cli = get_redis_connection('code')
        # 3.2 指令操作
        # name, time, value
        redis_cli.setex(uuid, 60, text)

        # 4 返回图片二进制，这里不能用JsonResponse
        return HttpResponse(image, content_type='image/jpeg')
